package com.itcoon.cloud.framework.mybatis.typehandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ClassTypeHandler extends BaseTypeHandler<Class<?>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Class parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter == null ? null : parameter.getName());
    }

    @Override
    public Class<?> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        try {
            return rs.getString(columnName) == null ? null : Class.forName(rs.getString(columnName));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    @Override
    public Class<?> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        try {
            return rs.getString(columnIndex) == null ? null : Class.forName(rs.getString(columnIndex));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    @Override
    public Class<?> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        try {
            return cs.getString(columnIndex) == null ? null : Class.forName(cs.getString(columnIndex));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}
